<?php

class TestModuleAction extends fvAction {
    
    function __construct () {
        parent::__construct(fvSite::$Layoult);
    }

    function executeIndex() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
    function executeEdit() {
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }
    
    function executeSave() {
        $request = fvRequest::getInstance();
        
        if (!$TestModule = TestModuleManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $TestModule = new TestModule();
        }
        $mn = $request->getRequestParameter('mn');
        
//        if (!$TestModule->isNew() && ($mn['xmlfile'] != '') && ($mn['xmlfile'] != $TestModule['xmlfile'])) {
//            $TestModule->deleteXmlfile('xmlfile');
//        }
        
        $TestModule->updateFromRequest($mn);
        
        if ($TestModule->save()) {
            
            if ($mn['xmlfile'] != '') {
                $TestModule->saveUploadFile('xmlfile', fvSite::$fvConfig->get('path.upload.tmp_dir') . $mn['xmlfile'], 'xml');
                $XmlQuestions = file_get_contents($TestModule->getXmlFileDir().$mn['xmlfile']);
                $XmlQuestionsArray = $TestModule->Array2XML($XmlQuestions);
                $question[] = array();
                foreach ($XmlQuestionsArray[0]['elements'] as $key => $value)
                {
                	$question[$key]['text'] = $value['elements'][0]['text'];
                	echo $TestModule->getPk();
                	$question[$key]['testmodule_id'] = $TestModule->getPk();
                	foreach ($value['elements'][1]['elements'] as $key_ans => $value_ans){
                		$temp_array[$key_ans]['answer'] = $value_ans['text'];
                		$temp_array[$key_ans]['correct'] = intval($value_ans['attributes']['correct']);
                		$question[$key]['answers'] = $temp_array;
                	}
                	$Question = new Question();
                	$Question->updateFromRequest($question[$key]);
                	$Question->save();
                }
                
//                echo "<pre>";print_r($question);echo "</pre>";die();
            }
             
            fvResponce::getInstance()->setHeader('Id', $TestModule->getPk());
            $this->setFlash("Данные успешно сохранены", self::$FLASH_SUCCESS);
            fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/?id=". $TestModule->getPk());        
        } else { 
            fvResponce::getInstance()->setHeader('X-JSON', json_encode($TestModule->getValidationResult()));
            $this->setFlash("Ошибка при сохранении данных проверте правильность введенных данных", self::$FLASH_ERROR);
        }
        
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_AJAX_CALL;
        else return self::$FV_OK;
    }

    private function getObjectById($array, $id) {
        foreach ($array as $key => $object) {
            if ($object->getPk() == $id) return $key;
        }
        return -1;
    }
    
    function executeDelete() {
        $request = fvRequest::getInstance();
        if (!$TestModule = TestModuleManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
            $this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
        } else {
            $TestModule->delete();
            $this->setFlash("Данные успешно удалены", self::$FLASH_SUCCESS);
        }
        
        fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/");
        if (fvRequest::getInstance()->isXmlHttpRequest())
            return self::$FV_NO_LAYOULT;
        else return self::$FV_OK;
    }
    
    function executeUploadxmlfile () {
        $r = fvRequest::getInstance();
        if ($r->isFileUpload('xmlfile') && ($r->checkUploadFile('xmlfile') == fvRequest::ERROR_SUCCESS)) {
            $tmp_dir = fvSite::$fvConfig->get('path.upload.tmp_dir');
            $fileName = $r->getUploadFileName('xmlfile');
            $r->saveUploadData('xmlfile', $tmp_dir . $fileName);

            fvParams::getInstance()->setParameter(fvRoute::getInstance()->getModuleName() . "/filename", $fileName);
        }

        return self::$FV_AJAX_CALL;
    }

    function executeDeleteXmlfile () {
        $TestModule = TestModuleManager::getInstance()->getByPk(fvRequest::getInstance()->getRequestParameter('id'));
        
        if (!is_object($TestModule) || $TestModule['xmlfile'] != fvRequest::getInstance()->getRequestParameter('xmlfile')) {
            if (is_object($TestModule) && $TestModule->hasFile('xmlfile')) {
                fvResponce::getInstance()->setHeader('X-JSON', json_encode(
                    array(
                        'xmlfile' => $TestModule->getFileDir(true) . $TestModule->getFileName('xmlfile'),
                    )
                ));
            }
            if (is_file(fvSite::$fvConfig->get('path.upload.tmp_name').fvRequest::getInstance()->getRequestParameter('xmlfile'))) {
                unlink(fvSite::$fvConfig->get('path.upload.tmp_name').fvRequest::getInstance()->getRequestParameter('xmlfile'));
            }
        } else {
            if (is_file(fvSite::$fvConfig->get('path.upload.tmp_name').$TestModule['xmlfile'])) {
                unlink(fvSite::$fvConfig->get('path.upload.tmp_name').$TestModule['xmlfile']);
            }
            $TestModule->deleteImages('image');
        }
        
        $this->setFlash("Файл успешно удален", fvAction::$FLASH_SUCCESS);
        
        return self::$FV_AJAX_CALL;
    }
}

?>
